﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web.UI;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;

using SPListNames = Kiiro.Common.Utility.Constants.SPListNames;
using PortalFileUrls = Kiiro.Common.Utility.Constants.PortalFileUrls;
using ProjectFileUrls = Kiiro.Common.Utility.Constants.ProjectFileUrls;

namespace Kiiro.SiteDefinition.ControlTemplates
{
    public partial class NavigationMain : KiiroUserControl
    {
        protected override void OnPreRender ( EventArgs e )
        {
            try
            {
                List<NavigationItem> tabs = new List<NavigationItem> ( );
                List<NavigationItem> navItems = new List<NavigationItem> ( );
                List<NavigationItem> projectNavItems = new List<NavigationItem> ( );

                string item = "<li class='{0}'><a href='{1}' class='{2}'><span>{3}</span></a></li>";
                litNavHtml.Text = "";

                string siteLevel = IsPortal ? "Portal" : "Project";

                try
                {
                    using ( SPWeb web = SPHelpers.GetPortalWeb ( Base.SiteCollectionId, Base.ServerRelativeUrl ) )
                    {
                        SPList list = web.Lists [ Constants.SPListNames.MainNavigation ];

                        if ( list != null )
                        {
                            navItems = list.Items.Cast<SPListItem> ( ).Select ( li => new NavigationItem ( li ) ).ToList ( );
                            navItems = navItems
                                .Where ( i => i.SiteLevel == siteLevel && i.IsVisible )
                                    .ToList ( );
                        }
                    }
                }
                catch { }
                
                if ( IsProject )
                {
                    try
                    {
                        using ( SPWeb web = SPHelpers.GetWeb ( Base.SiteCollectionId, Base.ServerRelativeUrl ) )
                        {
                            SPList list = web.Lists [ Constants.SPListNames.MainNavigation ];

                            if ( list != null )
                            {
                                projectNavItems = list.Items.Cast<SPListItem> ( ).Select ( li => new NavigationItem ( li ) ).ToList ( );
                                projectNavItems = projectNavItems
                                    .Where ( i => i.IsVisible )
                                        .ToList ( );

                                navItems.AddRange ( projectNavItems );
                            }
                        }
                    }
                    catch { }
                }

                navItems = navItems.OrderBy ( x => x.Sequence ).ThenBy ( x => x.Title ).ToList ( );

                // one-time permission checks (to reduce unnecessary overhead)
                bool isFullAdminCheck = Base.CurrentUser.IsAdministrator && !Base.CurrentUser.ManageProjectsOnly;
                bool isPortalMemberCheck = Base.CurrentUser.Groups.Contains ( KiiroGroup.PortalMember ) && Base.CurrentUser.Login != Constants.Security.AD_AUTH_USERS_DOMAIN_GROUP_NAME;
                bool isProjectOwnerCheck = Base.PermissionBitsProjects [ 2 ] || Base.PermissionBitsProjects [ 3 ];

                // special pages check
                bool foundList = false;
                using ( SPWeb web = SPHelpers.GetWeb ( Base.SiteCollectionId, Base.ServerRelativeUrl ) )
                {
                    foundList = web.Lists.Cast<SPList> ( ).Count ( x => x.BaseTemplate.ToString ( ) == "50008" ) > 0;
                }
                
                bool foundWebPartPage = IsPortal ? 
                    SetupModel.IsWPSandboxActivated ( Base.SiteCollectionId, Base.ServerRelativeUrl ) : 
                    ProjectsModel.IsWPSandboxActivated ( Base.SiteCollectionId, Base.ServerRelativeUrl );

                foreach ( NavigationItem navItem in navItems )
                {
                    bool canAddLink = false;
                    navItem.GroupVisibility.ForEach (
                        delegate ( KiiroGroup kg )
                        {
                            if ( !canAddLink )
                            {
                                if ( kg == KiiroGroup.PortalOwner )
                                    canAddLink = isFullAdminCheck;
                                else if ( kg == KiiroGroup.PortalMember )
                                    canAddLink = isPortalMemberCheck;
                                else if ( kg == KiiroGroup.ProjectOwner )
                                    canAddLink = isProjectOwnerCheck;
                                else if ( kg == KiiroGroup.ProjectMember )
                                    canAddLink = true;
                                else if ( kg == KiiroGroup.Visitor )
                                    canAddLink = true;
                            }
                        } );

                    if ( navItem.TargetUrl == PortalFileUrls.Lists )
                        canAddLink &= foundList;

                    if ( navItem.TargetUrl == PortalFileUrls.WPSandbox )
                    {
                        canAddLink &= foundWebPartPage;
                        string navText = IsPortal ?
                            SetupModel.GetWPSandboxNavText ( Base.SiteCollectionId, Base.ServerRelativeUrl ) :
                            ProjectsModel.GetWPSandboxNavText ( Base.SiteCollectionId, Base.ServerRelativeUrl );

                        if ( navItem.Title != navText )
                            navItem.Title = navText;
                    }

                    if ( canAddLink )
                    {
                        litNavHtml.Text +=
                            String.Format ( item,
                            /* 0 */ litNavHtml.Text == "" ? "borderless" : "",
                            /* 1 */ ( navItem.TargetUrl.StartsWith ( "/" ) ? Base.ServerRelativeUrl : "" ) + navItem.TargetUrl,
                            /* 2 */ IsSelected ( navItem ) ? "selected" : "",
                            /* 3 */ navItem.Title );
                    }
                }

                // Site Actions
                tcSiteActions.Visible = isFullAdminCheck;
            }
            catch ( Exception ex )
            {
                ExceptionManagement.ExceptionManager.HandleException ( ex, true );
            }

            base.OnPreRender ( e );
        }

        private bool IsSelected ( NavigationItem navItem )
        {
            string thisPage = RequestFilePath ( );
            List<string> hilite = navItem.PageHiLiteCollection;
            bool selected = hilite.Exists ( x => x.ToLower ( ) == thisPage );
            return selected;
        }

        private string RequestFilePath ( )
        {
            return Request.FilePath.Substring ( Request.FilePath.LastIndexOf ( "/" ) ).ToLower ( );
        }
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/CONTROLTEMPLATES/Kiiro/NavigationMain.ascx.cs $
 * 
 * 41    2/24/10 4:49p Camerons
 * 
 * 40    2/12/10 10:58a Camerons
 * 
 * 39    2/12/10 9:14a Camerons
 * 
 * 38    1/26/10 12:11p Camerons
 * 
 * 37    1/12/10 12:45p Camerons
 * 
 * 36    1/06/10 10:44p Camerons
 * 
 * 35    1/06/10 12:39p Camerons
 * 
 * 34    21/12/09 5:13p Adamw
 * 
 * 33    21/12/09 5:03p Adamw
 * 
 * 32    21/12/09 4:57p Adamw
 * added MainNav as webpart v1
 * 
 * 31    18/12/09 1:50p Adamw
 * 
 * 30    26/11/09 2:23p Shafia
 * 
 * 29    24/11/09 4:15p Shafia
 * Preview and Edit buttons for the editor now use same style as kiiro
 * buttons. Only need icons for the images
 * 
 * 28    9/11/09 11:02a Camerons
 * 
 * 27    7/11/09 1:14p Camerons
 * 
 * 26    6/11/09 7:34p Camerons
 * 
 * 25    6/11/09 3:17p Camerons
 * 
 * 24    27/10/09 5:13p Camerons
 * Remove build error
 * 
 * 23    10/26/09 11:03a Adamw
 * 
 * 22    19/10/09 10:13a Shafia
 * 
 * 21    19/10/09 10:12a Shafia
 * 
 * 20    7/10/09 6:01p Camerons
 * 
 * 19    5/10/09 1:56p Camerons
 * Implement re-adding of the guest account code to the PortalProvisioner
 * and UserModel. Enable and disable various UI elements for guest account
 * 
 * 18    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 17    29/09/09 5:41p Camerons
 * 
 * 16    29/09/09 12:40p Shafia
 * Implemented WebPart at project level
 * 
 * 15    28/09/09 3:38p Camerons
 * 
 * 14    24/09/09 4:16p Camerons
 * 
 * 13    8/21/09 12:12p Camerons
 * Added case for WPSandbox to DetermineSelectedTab method
 * 
 * 12    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/